package com.xm.thread.wait2notify;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 方案1：使用Lock + Condition（精细控制）
 * 优势：
 *   支持多条件变量（不同等待条件）
 *   可设置超时时间（awaitNanos()/await(long time, TimeUnit unit)）
 *   更清晰的代码结构
 */
@Slf4j
public class WaitToNotify02 {
    private final Lock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    private final int[] buffer = new int[10];
    private int count = 0;

    public void put(int value) {
        lock.lock();
        try {
            while (count == buffer.length) {
                notFull.await();// 等待“非满”条件
            }
            buffer[count++] = value;
            notEmpty.signal();// 触发“非空”条件
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public int get() {
        lock.lock();
        try {
            while (count == 0) {
                notEmpty.await();// 等待“非空”条件
            }
            int value = buffer[--count];
            notFull.signal();// 触发“非满”条件
            return value;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }


}
